﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using KeanuMvc.Reference;
using HISModels.Entities;
using System.Net.Http;
using HISModels.ViewModel;

namespace HISRestServices.Services {

    [ServiceContract()]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class Purchase : BaseServices, IDisposable {

        #region Field
        private HttpStatusCode statusCode = new HttpStatusCode();
        private string detailMessage = string.Empty;
        #endregion

        #region Supplier
        [WebGet(UriTemplate = "supplier/{id}")]
        public HttpResponseMessage<Supplier> GetSupplierById(int id) {
            HttpResponseMessage<Supplier> returnValue = null;
            Supplier supplier = null;
            try {
                supplier = new Supplier();

                var a = (from b in AppContext.Suppliers.Include("Addresses")
                         where b.Id == id && b.RecordStatus == 1
                         select b).First();

                supplier = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<Supplier>(statusCode);
            returnValue.Content = new ObjectContent<Supplier>(supplier);
            if (supplier == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;

        }

        [WebInvoke(Method = "POST", UriTemplate = "supplier/paging/")]
        public HttpResponseMessage<DataTablesNet> GetSupplierPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            string code = string.Empty;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                code = data[0].Split('=')[1].NullSafeToString();

                //var a = from b in AppContext.Suppliers
                //        join c in AppContext.Addresses on b.Id equals c.SupplierId
                //        where b.RecordStatus == 1 && c.TypeId == 1
                //        select new
                //        {
                //            b.Id,
                //            name = b.CodeValue,
                //            b.BankId,
                //            b.ContactPerson,                     
                //            b.Phone,
                //            b.Mobile,
                //            c.AddressDesc

                //        };
                var a = from b in AppContext.Suppliers
                        where b.RecordStatus == 1
                        select b;

                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.CodeValue.Contains(code));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "supplier/")]
        public HttpResponseMessage<Supplier> InsertSupplier(Supplier paramObject) {
            HttpResponseMessage<Supplier> returnValue = null;
            try {
                if (AppContext.Suppliers.Where(d => d.CodeValue == paramObject.CodeValue && d.RecordStatus == 1).Count() > 0) {
                    detailMessage = "Data is already exist in Database!";
                    paramObject = null;
                } else {
                    paramObject.RecordStatus = 1;
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    foreach (var item in paramObject.Addresses) {
                        paramObject.RecordStatus = 1;
                        AppContext.Entry(item).State = System.Data.EntityState.Added;
                    }
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;

                }
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Supplier>(statusCode);
                returnValue.Content = new ObjectContent<Supplier>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "supplier/")]
        public HttpResponseMessage<Supplier> UpdateSupplier(Supplier paramObject) {
            HttpResponseMessage<Supplier> returnValue = null;
            try {
                if (AppContext.Suppliers.Where(d => d.CodeValue == paramObject.CodeValue && d.Id != paramObject.Id).Count() > 0) {
                    detailMessage = "Name of Supplier is already exist in Database!";
                    paramObject = null;
                } else {
                    //var supplierEntity = AppContext.Suppliers.First(p => p.Id == paramObject.Id);
                    // set supplier entity
                    //supplierEntity.BankId = paramObject.BankId;

                    //AppContext.SaveChanges(UserId);


                    foreach (var item in paramObject.Addresses) {
                        AppContext.Entry(item).State = System.Data.EntityState.Modified;
                    }

                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    statusCode = HttpStatusCode.OK;
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Supplier>(statusCode);
                returnValue.Content = new ObjectContent<Supplier>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "supplier/")]
        public HttpResponseMessage<Supplier> DeleteSupplierByID(int id) {
            HttpResponseMessage<Supplier> returnValue = null;
            Supplier supplier = null;
            try {
                supplier = AppContext.Suppliers.Where(d => d.Id == id).First();

                supplier.RecordStatus = 0;
                AppContext.Entry(supplier).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Supplier>(statusCode);
                returnValue.Content = new ObjectContent<Supplier>(supplier);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Supplier Type
        [WebGet(UriTemplate = "supplier/type/")]
        public HttpResponseMessage<List<RefSupplierType>> GetListSuppType() {
            HttpResponseMessage<List<RefSupplierType>> returnValue = null;
            List<RefSupplierType> refsupptype = null;
            try {
                refsupptype = (from h in AppContext.RefSupplierTypes select h).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<RefSupplierType>>(statusCode);
                returnValue.Content = new ObjectContent<List<RefSupplierType>>(refsupptype);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "supplier/type/{id}")]
        public HttpResponseMessage<RefSupplierType> GetSuppTypeById(int id) {
            HttpResponseMessage<RefSupplierType> returnValue = null;
            RefSupplierType refsuptype = null;
            try {
                refsuptype = (from h in AppContext.RefSupplierTypes
                              where h.Id == id
                              select h).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<RefSupplierType>(statusCode);
                returnValue.Content = new ObjectContent<RefSupplierType>(refsuptype);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "supplier/type/paging/")]
        public HttpResponseMessage<DataTablesNet> GetSuppTypePaging(PostDataTablesNet pagingSearch) {
            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] data = null;
            string name = string.Empty;


            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');

                name = data[0].Split('=')[1].NullSafeToString().Trim();


                var a = from b in AppContext.RefSupplierTypes
                        select b;

                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.NameValue.Contains(name));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {

                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "supplier/type/")]
        public HttpResponseMessage<RefSupplierType> InsertSuppType(RefSupplierType paramObject) {
            HttpResponseMessage<RefSupplierType> returnValue = null;
            try {
                if (AppContext.RefSupplierTypes.Where(d => d.NameValue == paramObject.NameValue).Count() > 0) {
                    detailMessage = "Name of Supplier Type is already exist in Database!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<RefSupplierType>(statusCode);
                returnValue.Content = new ObjectContent<RefSupplierType>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "supplier/type/")]
        public HttpResponseMessage<RefSupplierType> UpdateSuppType(RefSupplierType paramObject) {
            HttpResponseMessage<RefSupplierType> returnValue = null;
            try {
                if (AppContext.RefSupplierTypes.Where(d => d.Id != paramObject.Id && d.NameValue == paramObject.NameValue).Count() > 0) {
                    detailMessage = "Name of Supplier Type is already exist in Database!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<RefSupplierType>(statusCode);
                returnValue.Content = new ObjectContent<RefSupplierType>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "supplier/type/")]
        public HttpResponseMessage<RefSupplierType> RemoveSuppType(int id) {
            HttpResponseMessage<RefSupplierType> returnValue = null;
            RefSupplierType refsuptype = null;
            try {
                refsuptype = AppContext.RefSupplierTypes.Where(d => d.Id == id).First();

                AppContext.Entry(refsuptype).State = System.Data.EntityState.Deleted;
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<RefSupplierType>(statusCode);
                returnValue.Content = new ObjectContent<RefSupplierType>(refsuptype);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion

        #region Purchase
        [WebGet(UriTemplate = "purchase/{id}")]
        public HttpResponseMessage<PurchaseRequsition> GetPurchaseById(int id) {
            HttpResponseMessage<PurchaseRequsition> returnValue = null;
            PurchaseRequsition purchase = null;
            try {
                purchase = AppContext.PurchaseRequsitions.Where(d => d.Id == id).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PurchaseRequsition>(statusCode);
                returnValue.Content = new ObjectContent<PurchaseRequsition>(purchase);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "purchase/paging/")]
        public HttpResponseMessage<DataTablesNet> GetPurchasePaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;
            string start = string.Empty;
            string end = string.Empty;

            DateTime starttime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            string code = string.Empty;

            try {
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');
                start = data[0].Split('=')[1].NullSafeToString();
                end = data[1].Split('=')[1].NullSafeToString();
                code = data[2].Split('=')[1].NullSafeToString();

                var a = from b in AppContext.PurchaseRequsitions
                        join c in AppContext.RefDocumentStatuses on b.DocumentStatusId equals c.Id
                        join d in AppContext.SysMemberships on b.RequestBy equals d.UserId
                        join e in AppContext.MemberEmployees on d.Id equals e.MembershipId
                        join f in AppContext.Employees on e.EmployeeId equals f.Id
                        select new {
                            purchaseid = b.Id,
                            b.CodeValue,
                            b.NeedTime,
                            b.ReleasedDate,
                            b.RequestBy,
                            DocumentStatus = c.NameValue,                           
                            name = f.FirstName+" "+f.LastName                          
                        };

                paging.iTotalRecords = a.Count();

                if (start != string.Empty || end != string.Empty) {
                    starttime = Convert.ToDateTime(start);
                    endtime = Convert.ToDateTime(end);

                    a = a.Where(p => p.ReleasedDate >= starttime && p.ReleasedDate <= endtime);

                }

                a = a.Where(q => q.CodeValue.Contains(code));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.purchaseid);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "purchasedetail/paging/")]
        public HttpResponseMessage<DataTablesNet> GetPurchaseDetailPaging(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            string[] data = null;

            string code = string.Empty;

            try {

                code = data[0].Split('=')[1].NullSafeToString();



                var a = from b in AppContext.PurchaseRequsitionDetails
                        select b;

                a = a.Where(q => q.ItemCode.Contains(code));

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.ItemCode);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        #endregion

        void IDisposable.Dispose() {
            try {
                base.Dispose();
                GC.SuppressFinalize(this);
            } catch { }
        }
    }
}